package com.oauth.controller;

import com.alibaba.druid.sql.dialect.mysql.ast.MysqlForeignKey;
import com.oauth.config.OauthConfig;
import com.oauth.model.OpenToken;
import com.oauth.resmodel.CheckResource;
import com.oauth.service.OauthTokenService;
import com.oauth.service.OpenClientService;
import com.oauth.service.OpenTokenService;
import com.oauth.util.AuthUtil;
import org.apache.oltu.oauth2.as.issuer.MD5Generator;
import org.apache.oltu.oauth2.as.issuer.OAuthIssuer;
import org.apache.oltu.oauth2.as.issuer.OAuthIssuerImpl;
import org.apache.oltu.oauth2.as.request.OAuthTokenRequest;
import org.apache.oltu.oauth2.as.response.OAuthASResponse;
import org.apache.oltu.oauth2.as.validator.AuthorizationCodeValidator;
import org.apache.oltu.oauth2.as.validator.PasswordValidator;
import org.apache.oltu.oauth2.as.validator.RefreshTokenValidator;
import org.apache.oltu.oauth2.common.OAuth;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.apache.oltu.oauth2.common.message.OAuthResponse;
import org.apache.oltu.oauth2.common.message.types.GrantType;
import org.apache.oltu.oauth2.common.message.types.TokenType;
import org.apache.oltu.oauth2.common.token.BasicOAuthToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.Instant;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 访问令牌控制器  推荐使用授权码模式
 * 授权码模式
 * 简化模式
 * 密码模式
 * 客户端模式
 * Created by yangjianbo on 2016/9/24.
 */
@RestController
@RequestMapping("oauth")
public class AccessTokenController {

    @Autowired
    private OauthTokenService oauthTokenService;

    //http://localhost:8080/accessToken?grant_type=authorization_code&client_secret=111&code=46733f8fd465e038e8ecd2a02bec3dd1&client_id=111&redirect_uri=http://www.baidu.com
    @RequestMapping(value = "/token",method = RequestMethod.POST)
    public Object accessToken(HttpServletRequest request) throws OAuthProblemException, OAuthSystemException {

        //构建OAuth请求
        OAuthTokenRequest oauthRequest = new OAuthTokenRequest(request);
        if(GrantType.AUTHORIZATION_CODE.toString().equals(oauthRequest.getGrantType())){
            AuthorizationCodeValidator authorizationCodeValidator=new AuthorizationCodeValidator();
            authorizationCodeValidator.performAllValidations(request);
            BasicOAuthToken basicOAuthToken=oauthTokenService.tokenByCode(oauthRequest.getClientId(),oauthRequest.getClientSecret(),
                    oauthRequest.getCode(),oauthRequest.getRedirectURI(),oauthRequest.getParam(OAuth.OAUTH_SCOPE));
            //生成OAuth响应
            OAuthResponse response = AuthUtil.convert(basicOAuthToken);
            //根据OAuthResponse生成ResponseEntity
            return new ResponseEntity(
                    response.getBody(), HttpStatus.valueOf(response.getResponseStatus()));

        }else if (GrantType.CLIENT_CREDENTIALS.toString().equals(oauthRequest.getGrantType())){
            RefreshTokenValidator refreshTokenValidator=new RefreshTokenValidator();
            refreshTokenValidator.performAllValidations(request);
            BasicOAuthToken basicOAuthToken=oauthTokenService.tokenByClient(
                    oauthRequest.getClientId(),oauthRequest.getClientSecret(),oauthRequest.getParam(OAuth.OAUTH_SCOPE));
            //生成OAuth响应
            OAuthResponse response = AuthUtil.convert(basicOAuthToken);
            //根据OAuthResponse生成ResponseEntity
            return new ResponseEntity(
                    response.getBody(), HttpStatus.valueOf(response.getResponseStatus()));
        }else if(GrantType.PASSWORD.toString().equals(oauthRequest.getGrantType())){
            PasswordValidator passwordValidator=new PasswordValidator();
            passwordValidator.performAllValidations(request);
            return null;
        }else if(GrantType.REFRESH_TOKEN.toString().equals(oauthRequest.getGrantType())){
            RefreshTokenValidator refreshTokenValidator=new RefreshTokenValidator();
            refreshTokenValidator.performAllValidations(request);
            BasicOAuthToken basicOAuthToken=oauthTokenService.tokenByRefresh(oauthRequest.getRefreshToken(),oauthRequest.getParam(OAuth.OAUTH_SCOPE));
            //生成OAuth响应
            OAuthResponse response = AuthUtil.convert(basicOAuthToken);
            //根据OAuthResponse生成ResponseEntity
            return new ResponseEntity(
                    response.getBody(), HttpStatus.valueOf(response.getResponseStatus()));
        }
        else{
            throw OAuthProblemException.error("不支持该授权类型");
        }
    }

    @RequestMapping(value = "/check",method = RequestMethod.POST)
    @ResponseBody
    public CheckResource check(String access_token,String secope) throws OAuthProblemException {
        //断言令牌是否能访问该资源
        Boolean flag=oauthTokenService.isEnable(access_token,secope);
        CheckResource checkResource=new CheckResource(flag,access_token,secope);
        return checkResource;
    }
}
